********************************************************************************
* 
* Creating tables and figures for paper 
*   
********************************************************************************

clear all 

global data "E:\Data"
global paper "C:\Users\cpsresearch\Dropbox (MIT)\Child protection research\writing"

use "$data\Processed\MainDataset", clear
egen FE_oy=group(regional_office_invN intake_dt_y)
egen tag=tag(refer_id client_id)
tab tag 
bys mci_uniq_id9: egen nbofref=total(tag)
bys client_id: egen everregistered=max(registered)
bys client_id: egen evervoted=max(voted_post2013)
bys client_id: egen evernotregistered=min(registered)
bys client_id: egen evernotvoted=min(voted_post2013)


*Nbs of NT,AT and Compliers 
summ propacceptN propanyremoved3mN if nbreferrals_invN>=10 //100% compliers for accept, and 40% for removals 
foreach x in propacceptN propanyremoved3mN {
	preserve 
	keep if nbreferrals_invN>=70 & screenin==1
	bys regional_office_invN intake_dt_y: egen minp=min(`x')	
	bys regional_office_invN intake_dt_y: egen maxp=max(`x')	
	summ minp maxp 
	restore 
}
//for 10+ investigations: 12%-77% for accept, 0.005-0.255 for removals 
//for 70+ investigations: 19%-63% for accept, 0.04-0.17 for removals 

* Distributions of tendency measures 
graph twoway (kdensity propacceptresN,lcolor(black))(kdensity propanyremoved3mresN,lcolor(gray) lpattern(longdash_dot)) if nbreferrals_invN>=10, graphregion(color(white)) bgcolor(white) xtitle("Tendency") ytitle("Density") legend(label(1 "Open a Case") label(2 "Remove")) //note(Restricted to investigators with at least 10 referrals.)
	graph export "$paper\DensityProp.png", replace 


***********************************************
* Table 1 / CPS Descriptive Statistics Table 
***********************************************
frame put if tag==1, into(cps)
frame change cps 

summ listedallegation* //most frequent listed allegations are 22, 9, 8,16, 4 and 11 
*Table of Descriptive Statistics for Referrals 
label var screenin "Investigated"
label var accept "Opened a Child Welfare Case"
label var anyremoved3m "Child Removed within 3 months"
label var anyremoved1y "Child Removed within 1 year"
label var listedallegation22 "Parent Struggling"
label var listedallegation8 "Parent Drug Abuse"
label var listedallegation9 "Failure to Protect Child"
label var listedallegation16 "Physical Abuse"
gen abuse=listedallegation16==1 | listedallegation17==1
label var abuse "Allegation of Physical or Sexual Abuse"

*Combined Table of Descriptive Statistics for Paper 
  
eststo clear 
preserve 
	bys refer_id: keep if _n==1 
	foreach x in screenin accept anyremoved3m anyremoved1y abuse {
	    replace `x'=`x'*100
		local previousname: variable label `x'
		label var `x' "`previousname' (\%)"
	}
	estpost summ screenin accept anyremoved3m abuse //anyremoved1y  
	local countofref `e(N)'
	eststo 
	esttab using "$paper\ComboDesc.tex", cell("mean(fmt(0))") collabels(none) label  nomtitles nonumbers replace booktabs nostar unstack nonotes nogaps posthead(\\ \multicolumn{2}{l}{\textit{Panel A: Child Welfare Referrals }} \\ ) prefoot("") postfoot("") noobs prehead("\begin{tabular}{l*{1}{c}}" "\toprule")
restore 
preserve 
eststo clear 
	label var nbofref "Number of Referrals per Parent"
	bys mci_uniq_id9: keep if _n==1 
	estpost summ nbofref 
	eststo, addscalars(Nbref `countofref')
	esttab using "$paper\ComboDesc.tex", main(mean %8.1f) not /*aux(sd %8.1f)*/  nomtitles nonumbers label append booktabs nostar unstack nonotes nogaps prehead("") nolines  prefoot("") postfoot("") noobs scalars("Nbref Number of Referrals") 
restore 


*For continuous variables, keep SD but otherwise not
label var age_at_refer "Age" 
local variablestoinclude age_at_refer 
eststo clear 
eststo: estpost summ `variablestoinclude' 	

esttab using "$paper\ComboDesc.tex", main(mean %8.1f) not /*aux(sd %8.1f)*/  nomtitles nonumbers label append booktabs nostar unstack nonotes nogaps prehead( \\ \multicolumn{2}{l}{\textit{Panel B: Individual Characteristics}} \\) nolines  prefoot("") postfoot("") noobs 

eststo clear 
local variablestoinclude black2 missingrace female everregistered evervoted

preserve 
label var black2 "Black American"
label var missingrace "Race Missing"
label var everregistered "Ever Registered"
label var evervoted "Ever Voted"
foreach x in `variablestoinclude' { 
    replace `x'=`x'*100
	local previousname: variable label `x'
	label var `x' "`previousname' (\%)"
}
eststo clear 	
eststo: estpost summ `variablestoinclude'

esttab using "$paper\ComboDesc.tex", cell(mean(fmt(0))) collabels(none) nomtitles nonumbers label append booktabs nostar unstack nonotes nogaps prehead("") nolines  prefoot("\midrule ") postfoot("\bottomrule \end{tabular}")
restore 

*Characterizing perpetrators 
replace aprp=0 if aprp==.
reg aprp age_at_refer black2 missingrace female everregistered evervoted
foreach x in age_at_refer black2 missingrace female everregistered evervoted {
	ttest `x', by(aprp)
}

frame change default 
cap frame drop cps 



********************
* Complier analysis
********************

cap frame change default 
frame copy default complier, replace 
frame change complier
tempname dataname
tempfile dataresults
capture postclose `dataname'
postfile `dataname' str6 variableend str60 variablelabel str20 variablename  N RLLaccept RLLoo RLLrem using `dataresults', replace

 
egen tagindiv=tag(mci_uniq_id9)
summ nbofref if tag==1, det 
summ nbofref if tagindiv==1, det 
gen morethanoneref=nbofref>1 if nbofref<. 
gen youngadult=age_at_refer<26 if age_at_refer!=. 
summ age_at if tag==1,det  
gen belowmedianage=age_at<=r(p50)

foreach x in voted_post2013 registered { 
	gen v=`x' if evs_y<0
	bys mci_uniq_id9: egen prior`x'=max(v)
	drop v 
}
label var youngadult "\phantom{4}Young Adult"
label var morethanoneref "\phantom{5}More than One Referral"
label var priorregistered "\phantom{a}Ever Registered Prior to Referral"
label var priorvoted_post2013 "\phantom{b}Ever Voted Prior to Referral"
label var listedallegation22 "\phantom{6}Allegation: Parent Struggling"
label var listedallegation8 "\phantom{7}Allegation: Parent Drug Abuse"
label var listedallegation9 "\phantom{8}Allegation: Failure to Protect Child"
label var listedallegation16 "\phantom{9}Allegation: Physical Abuse"
label var black2 "\phantom{1}Black American"
label var female "\phantom{3}Woman"
label var missingrace "\phantom{2}Missing Race"

local fin N
reg accept propacceptres`fin' i.FE_oy if tag==1
	local coeffA=_b[propacceptres`fin']
reg openonly propopenonlyres`fin' propanyremoved3mres`fin' i.FE_oy  if tag==1,  vce(cluster caseworker_id_invN) 
			local coeffO=_b[propopenonlyres`fin']
		reg anyremoved3m propopenonlyres`fin' propanyremoved3mres`fin' i.FE_oy  if tag==1,  vce(cluster caseworker_id_invN) 
			local coeffR=_b[propanyremoved3mres`fin']

foreach x in youngadult black2 missingrace female morethanoneref listedallegation22 listedallegation8 listedallegation9 listedallegation16   priorregistered priorvoted_post2013 { 
			dis "`x'"
			count if `x'==1 & tag==1 
			local N=`r(N)'
			local name: variable label `x'
			reg accept propacceptres`fin' i.FE_oy if tag==1  & `x'==1, vce(cluster caseworker_id_invN) 
				local coeffhereA=_b[propacceptres`fin']
			reg openonly propopenonlyres`fin' propanyremoved3mres`fin' i.FE_oy if tag==1  & `x'==1,  vce(cluster caseworker_id_invN) 
				local coeffhereO=_b[propopenonlyres`fin']
			reg anyremoved3m propopenonlyres`fin' propanyremoved3mres`fin' i.FE_oy if tag==1  & `x'==1,  vce(cluster caseworker_id_invN) 
				local coeffhereR=_b[propanyremoved3mres`fin']
			post `dataname' ("`fin'") ("`name'") ("`x'") (`e(N)') (`coeffhereA'/`coeffA') (`coeffhereO'/`coeffO') (`coeffhereR'/`coeffR') 
		}

postclose `dataname'

use `dataresults', clear 
keep variablelabel RLLaccept RLLrem N 
order variablelabel RLLaccept RLLrem N 
foreach x in RLLaccept RLLrem {
	replace `x'=(round(`x',0.01)-1)*100
}
label var variablelabel "Characteristic"
rename N Nobs

eststo clear 
estpost tabstat RLLaccept RLLrem Nobs, by(variablelabel)
esttab using "$paper\Compliers.tex", cells("RLLaccept(label(Opened a Case)) RLLrem(label(Child Removed)) Nobs(label(N))") noobs nomtitles nonumbers drop(Total) varwidth(30) tex replace varlabels(`e(labels)') 



frame change default 
frame drop complier 

***********************************************
* Table 2 / Political Outcomes Descriptive Stats 
***********************************************

cap program drop addcolumn 
program define addcolumn, eclass
matrix m = [`1',`2',`3',`4']
matrix colnames m = registered rep dem voted_post2013
ereturn scalar N=`5'
ereturn matrix mean=m
end


label var rep "Registered as Republican" 
label var dem "Registered as Democrat"
label var voted "Voted" 
label var voted_post2013 "Voted"
label var registered "Registered"

cap frame change default 
cap frame drop data2016 
frame put  if year==2016, into(data2016) 
frame change data2016 

egen oneindiv=tag(mci_uniq_id9)
eststo clear 
eststo: estpost summ registered rep dem voted_post2013 if oneindiv==1 

dis 924631/961595, 259534/961595, 539900/961595,650114/961595

eststo: addcolumn 0.96 0.27 0.56 0.68 961595	
/*Sources: 
CVAP from ACS https://www.census.gov/programs-surveys/decennial-census/about/voting-rights/cvap.2016.html#list-tab-1518558936
https://www.dos.pa.gov/VotingElections/OtherServicesEvents/VotingElectionStatistics/Pages/VotingElectionStatistics.aspx
https://www.dos.pa.gov/VotingElections/OtherServicesEvents/VotingElectionStatistics/Documents/2016%20Election%20VR%20Stats.pdf
County Democratic Republican OtherParties AllParties
Allegheny 539,900 259,534 125,197 924,631 */ 
dis 539900/924631*0.87, 259534/924631*0.87

esttab using "$paper\PolDesc.tex", cell(mean(fmt(2))) collabels(none) mtitles("CPS Individuals" "All Allegheny" ) label replace booktabs nostar unstack nonotes nogaps compress obslast  

eststo clear 
eststo: estpost summ registered rep dem voted_post2013 if oneindiv==1 & intake_dt_y==2016 
eststo: addcolumn 0.96 0.27 0.56 0.68 961595	
esttab using "$paper\PolDesc2016.tex", cell(mean(fmt(2))) collabels(none) mtitles("CPS Individuals" "All Allegheny" ) label replace booktabs nostar unstack nonotes nogaps compress obslast 



cap drop CPSmaxinter
gen CPSmaxinter=1 if screenin==0 
replace CPSmaxinter=2 if screenin==1&accept==0
replace CPSmaxinter=3 if accept==1 & anyremoved3m==0 
replace CPSmaxinter=4 if anyremoved3m==1 

*testing whether changes are statistically significant 
forval i=1/3 {
	foreach x in registered voted_post2013 {
		dis "`x'"
		ttest `x' if CPSmaxinter==`i' | CPSmaxinter==`i'+1, by(CPSmaxinter)
	}
}

preserve 
collapse registered voted_post2013, by(CPSmaxinter)
set obs 5 
replace CPSmaxinter=0 if _n==5 
replace registered=0.96 if _n==5 
replace voted_post2013=0.68 if _n==5 

label def valuesdef 0 "All Allegheny" 1 "Referred" 2 "Investigated" 3 "Case Opened" 4 "Removed" 
label val CPSmaxinter valuesdef
list * 
export excel using "$paper\Fig1data.xls", replace firstrow(varl) 

restore 

gen young=age_at_refer<=25
replace aprp=0 if aprp==. 
gen morethanoneref=nbofref>1 if nbofref<. 
gen abuse=listedallegation16==1 | listedallegation17==1
//gen abuse= ref_type=="CPS"
gen pre2016ref=intake_dt_y<2016

foreach x in black female young morethanoneref aprp pre2016ref abuse { 
	tempfile temp`x'
	preserve 
	collapse registered voted_post2013, by(`x')
	drop if `x'==.
	save `temp`x''
	list * 
	restore 
}
tempfile temp 
preserve 
use `tempblack', clear 
gen variable="Black" if black==1 
replace variable="White" if black==0
drop black  
save `temp'
use `tempfemale', clear 
gen variable="Women" if female==1 
replace variable="Men" if female==0
drop female 
append using `temp'  
save `temp', replace 
use `tempyoung', clear 
gen variable="Young" if young==1 
replace variable="Older" if young==0
drop young 
append using `temp' 
save `temp', replace 
use `tempaprp', clear 
gen variable="Perpetrators" if aprp==1 
replace variable="Others" if aprp==0
drop aprp 
append using `temp'
save `temp', replace 
use `tempmorethanoneref', clear 
gen variable="Multiple Referrals" if morethanoneref==1 
replace variable="One Referral" if morethanoneref==0
drop morethanoneref 
append using `temp'
save `temp', replace 
use `temppre2016ref', clear 
gen variable="Referred prior to 2016" if pre2016ref==1 
replace variable="Referred in 2016 or after" if pre2016ref==0
drop pre2016ref 
append using `temp'
save `temp', replace 
use `tempabuse', clear 
gen variable="Abuse" if abuse==1 
replace variable="Neglect" if abuse==0
drop abuse 
append using `temp'
list 
label var registered "Registered"
label var voted_post2013 "Voted"
label var variable "Group"
export excel using "$paper\DescriptiveBarGraphRace.xls", replace firstrow(varl) 


frame change default


*Figure Distribution of investigator caseload 
preserve 
keep if nbreferrals_invN>=10
keep if registered<. | voted_post2013<. 
drop if caseworker_id_invN==""
bys caseworker_id_invN: keep if _n==1 
summ nbreferrals_invN, det  
local median=`r(p50)'
local ninv=`r(N)'
* Distributions of tendency measures 
graph twoway (hist nbreferrals_invN,lcolor(black) freq color(gs12)) if nbreferrals_invN>=10, graphregion(color(white)) bgcolor(white) xtitle("Investigator Caseload Size") ytitle("Number of Investigators") xline(`median', lcolor(red)) xline(10, lcolor(green)) text(180 `median' "Median=`median'", placement(e) color(red)) text(257 10 "Minimum=10", placement(ne) color(green)) text(50 6000 "N=`ninv' investigators", placement(ne)) //note(Restricted to investigators with at least 10 referrals.)
	graph export "$paper\Caseload.png", replace 
restore 


***********************************************
* Table 3 / Effects on Voting and Registration of All CPS Margins  
***********************************************

cap drop *after 
gen after=evs_y>=0 
replace after=0 if screenin==0 
foreach x in propacceptresN propopenonlyresN propanyremoved3mresN  {
	gen `x'after=`x'*after 
	replace `x'after=0 if screenin==0 
}

cap erase "$paper\TableResults.tex"
file open myfile using "$paper\TableResults.tex", write replace
file write myfile "{"  _n
file write myfile "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n
file write myfile "\begin{longtable}{l*{3}{c}}" _n 
file write myfile "\toprule\endfirsthead\midrule\endhead\midrule\endfoot\endlastfoot" _n 
file write myfile "& &\multicolumn{2}{c}{Political Participation}" 
file write myfile "   \\\cmidrule(lr){2-2}\cmidrule(lr){3-4}" _n 
file write myfile " &\multicolumn{1}{c}{(1)} &\multicolumn{1}{c}{(2)}&\multicolumn{1}{c}{(3)}\\" _n 
file write myfile "&\multicolumn{1}{c}{First Stage}&\multicolumn{1}{c}{Registration}&\multicolumn{1}{c}{Voting}\\" _n 
file write myfile  "\midrule" _n



eststo clear 
preserve 

	*Row 1 - Accept
	*first stage 
	reghdfe accept propacceptresN if( tag==1 & nbreferrals_invN>=10), absorb(FE_oy) vce(cluster mci_uniq_id9) level(90) 
	local thiscoeff1=string(_b[propacceptresN],"%9.2f")
	local thisse1=string(_se[propacceptresN],"%9.2f")
	matrix R=r(table)
	local thispvalue1=R[rownumb(R,"pvalue"),colnumb(R,"propacceptresN")]
	local nbstars1 
	if `thispvalue1'<0.10 local nbstars1 * 
	if `thispvalue1'<0.05 local nbstars1 ** 
	if `thispvalue1'<0.01 local nbstars1 *** 
	*Outcomes 
	local i=1 
		foreach x in registered voted_post2013  {
			local i=`i'+1
			replace `x'=`x'*100
			reghdfe `x' propacceptresNafter after if  ( nbreferrals_invN>=10), absorb(personreferral year) vce(cluster mci_uniq_id9) level(90) 
			summ `x' if e(sample)==1 & after==0 & screenin==1 
			local  meanC`i'=string(r(mean),"%9.2f")
			local thiscoeff`i'=string(_b[propacceptresNafter],"%9.2f")
			local thisse`i'=string(_se[propacceptresNafter],"%9.2f")
			matrix R=r(table)
			local thispvalue`i'=R[rownumb(R,"pvalue"),colnumb(R,"propacceptresNafter")]
			local nbstars`i' 
			if `thispvalue`i''<0.10 local nbstars`i' * 
			if `thispvalue`i''<0.05 local nbstars`i' ** 
			if `thispvalue`i''<0.01 local nbstars`i' *** 
		} 
	file write myfile "Tendency to Open a Case& `thiscoeff1'`nbstars1' & `thiscoeff2'`nbstars2'  & `thiscoeff3'`nbstars3' \\" _n 
	file write myfile "& [`thisse1']  & [`thisse2']& [`thisse3'] \\" _n
		

	*Rows 2 and 3 
	*first stage 
	local i=0 
	foreach x in openonly anyremoved3m { 
		local i=`i'+1 
		reghdfe `x' propanyremoved3mresN propopenonlyresN if( tag==1 & nbreferrals_invN>=10), absorb(FE_oy) vce(cluster mci_uniq_id9) level(90) 
		local sampsize1=e(N)
		local cluster1=e(N_clust)
	local thiscoeff1`i'=string(_b[prop`x'resN],"%9.2f")
	local thisse1`i'=string(_se[prop`x'resN],"%9.2f")
	matrix R=r(table)
	local thispvalue1`i'=R[rownumb(R,"pvalue"),colnumb(R,"prop`x'resN")]
	local nbstars1`i' 
	if `thispvalue1`i''<0.10 local nbstars1`i' * 
	if `thispvalue1`i''<0.05 local nbstars1`i' ** 
	if `thispvalue1`i''<0.01 local nbstars1`i' *** 
	}
	
	*Outcomes 
	local i=1 
		foreach x in registered voted_post2013  {
			local i=`i'+1
			reghdfe `x' propanyremoved3mresNafter propopenonlyresNafter  after if  ( nbreferrals_invN>=10), absorb(personreferral year) vce(cluster mci_uniq_id9) level(90)
			local sampsize2=e(N)
			local cluster2=e(N_clust)
			local j=0 
			foreach x in openonly anyremoved3m { 
				local j=`j'+1 
			local thiscoeff`i'`j'=string(_b[prop`x'resNafter],"%9.2f")
			local thisse`i'`j'=string(_se[prop`x'resNafter],"%9.2f")
			matrix R=r(table)
			local thispvalue`i'`j'=R[rownumb(R,"pvalue"),colnumb(R,"prop`x'resNafter")]
			local nbstars`i'`j' 
			if `thispvalue`i'`j''<0.10 local nbstars`i'`j' * 
			if `thispvalue`i'`j''<0.05 local nbstars`i'`j' ** 
			if `thispvalue`i'`j''<0.01 local nbstars`i'`j' *** 
		} 
		}
	file write myfile "Tendency to Open a Case w/out a Removal& `thiscoeff11'`nbstars11' & `thiscoeff21'`nbstars21'  & `thiscoeff31'`nbstars31' \\" _n 
	file write myfile "& [`thisse11']  & [`thisse21']& [`thisse31'] \\" _n
	file write myfile "Tendency to Remove a Child& `thiscoeff12'`nbstars12' & `thiscoeff22'`nbstars22'  & `thiscoeff32'`nbstars32' \\" _n 
	file write myfile "& [`thisse12']  & [`thisse22']& [`thisse32'] \\" _n
file write myfile "\midrule" _n
file write myfile "Number of Obserations & `sampsize1' & `sampsize2' & `sampsize2' \\" _n
file write myfile "Number of Clusters & `cluster1' & `cluster2' & `cluster2' \\ " _n
file write myfile "Prior Mean & &`meanC2' & `meanC3' \\"
file write myfile "\bottomrule" _n
file write myfile "\end{longtable}" _n
file write myfile "}" _n
file close myfile
		
restore 		




***********************************************
* Table 4 / Table Showing not an Obvious Cancelling out of Effects across Groups 
***********************************************
gen midterm= year==2010 | year==2014|year==2018 | year==2022
gen presidential= year==2008 | year==2012|year==2016 | year==2020
gen abuse= ref_type=="CPS"
gen neglect=1-abuse 

cap program drop hettable 
program hettable, rclass 
args iflist ifname  

 if "`iflist'"!="if midterm==1" { 
reghdfe registered propacceptresNafter after `iflist' &  ( nbreferrals_invN>=10), absorb(personreferral year) vce(cluster mci_uniq_id9) level(90) 
	local thisobs1a=e(N)
	local thiscoeff1a=string(_b[propacceptresNafter],"%9.2f")
	local thisse1a=string(_se[propacceptresNafter],"%9.2f")
	matrix R=r(table)
	local thispvalue1a=R[rownumb(R,"pvalue"),colnumb(R,"propacceptresNafter")]
	local nbstars1a 
	if `thispvalue1a'<0.10 local nbstars1a * 
	if `thispvalue1a'<0.05 local nbstars1a ** 
	if `thispvalue1a'<0.01 local nbstars1a *** 
	
	cap noisily  reghdfe registered propopenonlyresNafter propanyremoved3mresNafter after  `iflist'  &(nbreferrals_invN>=10), absorb(personreferral year) vce(cluster mci_uniq_id9) level(90) 
	local thisobs2a=e(N)
	local thiscoeff2a=string(_b[propanyremoved3mresNafter],"%9.2f")
	local thisse2a=string(_se[propanyremoved3mresNafter],"%9.2f")
	matrix R=r(table)
	local thispvalue2a=R[rownumb(R,"pvalue"),colnumb(R,"propanyremoved3mresNafter")]
	local nbstars2a 
	if `thispvalue2a'<0.10 local nbstars2a * 
	if `thispvalue2a'<0.05 local nbstars2a ** 
	if `thispvalue2a'<0.01 local nbstars2a *** 
}

	reghdfe voted_post2013 propacceptresNafter after `iflist' &  ( nbreferrals_invN>=10), absorb(personreferral year) vce(cluster mci_uniq_id9) level(90) 
	local thisobs1=e(N)
	local thiscoeff1=string(_b[propacceptresNafter],"%9.2f")
	local thisse1=string(_se[propacceptresNafter],"%9.2f")
	matrix R=r(table)
	local thispvalue1=R[rownumb(R,"pvalue"),colnumb(R,"propacceptresNafter")]
	local nbstars1 
	if `thispvalue1'<0.10 local nbstars1 * 
	if `thispvalue1'<0.05 local nbstars1 ** 
	if `thispvalue1'<0.01 local nbstars1 *** 
	
	reghdfe voted_post2013 propopenonlyresNafter propanyremoved3mresNafter after  `iflist'  &(nbreferrals_invN>=10), absorb(personreferral year) vce(cluster mci_uniq_id9) level(90) 
	local thisobs2=e(N)
	local thiscoeff2=string(_b[propanyremoved3mresNafter],"%9.2f")
	local thisse2=string(_se[propanyremoved3mresNafter],"%9.2f")
	matrix R=r(table)
	local thispvalue2=R[rownumb(R,"pvalue"),colnumb(R,"propanyremoved3mresNafter")]
	local nbstars2 
	if `thispvalue2'<0.10 local nbstars2 * 
	if `thispvalue2'<0.05 local nbstars2 ** 
	if `thispvalue2'<0.01 local nbstars2 *** 

	local coeffrow `ifname' & `thiscoeff1a'`nbstars1a' & `thiscoeff2a'`nbstars2a' & `thiscoeff1'`nbstars1' & `thiscoeff2'`nbstars2' 
	local serow  & [`thisse1a']  & [`thisse2a']& [`thisse1']  & [`thisse2']
	local obsrow  & (`thisobs1a')  & (`thisobs2a')& (`thisobs1')  & (`thisobs2')

return local coeffrow `coeffrow' \\ 
return local serow `serow' \\
return local obsrow `obsrow' \\

end


local samplenames 1. All Adults,2. Mothers,3. Fathers,4. First Referral in Sample,5. Alleged Perpetrators,6. Black American,7. White American,8. Young Adults,9. Midterm Years,10. Presidential Years,11. Neglect,

local samples if _n<=_N,if parent==1 & female==1, if parent==1 & female==0,if firstref==1,if aprp==1,if black==1,if white==1,if age_at_refer<=25,if midterm==1,if presidential==1,if neglect==1  
//,if election_3m==1

local nsamples =length("`samplenames'")- length(subinstr("`samplenames'",",", "",.)) 
//count nb of commas to determine number of samples 

cap file close myfile
cap erase "$paper\TableHeterogeneity2.tex"
file open myfile using "$paper\TableHeterogeneity2.tex", write replace
file write myfile "{"  _n
file write myfile "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n
file write myfile "\begin{longtable}{l*{4}{c}}" _n 
file write myfile "\toprule\endfirsthead\midrule\endhead\midrule\endfoot\endlastfoot" _n 
file write myfile " &\multicolumn{2}{c}{Registered} &\multicolumn{2}{c}{Voted}\\" _n 
file write myfile "   \cmidrule(lr){2-3}\cmidrule(lr){4-5}" _n 
file write myfile " &\multicolumn{1}{c}{(1)} &\multicolumn{1}{c}{(2)}&\multicolumn{1}{c}{(3)} &\multicolumn{1}{c}{(4)}\\" _n 
file write myfile "& Opened a Case & Removed& Opened a Case & Removed\\" _n 
file write myfile  "\midrule" _n



eststo clear 
preserve 
	replace voted_post2013=voted_post2013*100
	replace registered=registered*100

	forval i=1/`nsamples' { 
	gettoken thisifstatement samples: samples, parse(",")
	gettoken comma samples: samples, parse(",")
	gettoken thisname samplenames: samplenames, parse(",")
	gettoken comma samplenames: samplenames, parse(",")
 
	
	hettable "`thisifstatement'" "`thisname'"
	file write myfile "`r(coeffrow)'" _n
	file write myfile "`r(serow)'" _n
	file write myfile "`r(obsrow)'" _n


} 
restore 
file write myfile "\bottomrule" _n
file write myfile "\end{longtable}" _n
file write myfile "}" _n
file close myfile



********************* 
* Graph on time from referral to voting period 
********************* 

cap frame change default 
cap frame drop regressiontime
frame copy default regressiontime, replace 
frame change regressiontime
label var voted_post2013 "Voted"
drop if evs_y>0 
tab evs_y, gen(eventd)
dis `r(r)'
forval j=1/`r(r)' { 
gen peventd`j'accept=propacceptresN*eventd`j'
replace peventd`j'accept=0 if screenin==0 
gen peventd`j'openonly=propopenonlyresN*eventd`j'
replace peventd`j'openonly=0 if screenin==0 
gen peventd`j'rem= propanyremoved3mresN*eventd`j'
replace peventd`j'rem=0 if screenin==0 
}

cap drop election* 

* In the months prior to election 
local month1 "Oct" 
local month2 "Sep"
local month3 "Aug"
local month6 "May"
foreach i in 1 2 3 6 {
gen election_`i'm=0 
replace election_`i'm=1 if intake_dt_mdy<=td(4Nov2008) & intake_dt_mdy>td(4`month`i''2008)
replace election_`i'm=1 if intake_dt_mdy<=td(2Nov2010) & intake_dt_mdy>td(2`month`i''2010)
replace election_`i'm=1 if intake_dt_mdy<=td(6Nov2012) & intake_dt_mdy>td(6`month`i''2012)
replace election_`i'm=1 if intake_dt_mdy<=td(4Nov2014) & intake_dt_mdy>td(4`month`i''2014)
replace election_`i'm=1 if intake_dt_mdy<=td(8Nov2016) & intake_dt_mdy>td(8`month`i''2016)
replace election_`i'm=1 if intake_dt_mdy<=td(6Nov2018) & intake_dt_mdy>td(6`month`i''2018)
replace election_`i'm=1 if intake_dt_mdy<=td(3Nov2020) & intake_dt_mdy>td(3`month`i''2020)
label var election_`i'm "Referral within `i' months prior to election"
}

gen election_all=1 

local prenb 2  
local postnb 0
	capture postclose time 
	postfile time str30 variable str4 timewindow accept_b accept_se using "$paper\TimetoElection.dta", replace
	
	tab evs_y if evs_y<=0
	local time0 `r(r)'
	local timebefore0=`time0'-1

*Variables for regressions 	
	foreach x in voted_post2013 registered {
		replace `x'=`x'*100
		local startevsnb=`time0'-`prenb'
		local endevsnb=`time0'+`postnb'
	foreach l in evsdummies variablesaccept variablesopenonly variablesrem {
		foreach prefix in pre post {
		local `prefix'`l' 
		}
	}
	foreach num of numlist `startevsnb'/`endevsnb' { 
		cap gen inveventd`num'=eventd`num'*screenin 
		*post-specification variables 
		local postevsdummies `postevsdummies' inveventd`num' 
		if `num'>=`time0' { 
			foreach u in accept openonly rem {
				local postvariables`u' `postvariables`u'' peventd`num'`u'
			}
		}
	}

	local name : variable label `x'
	*Post-trends analyses 
	foreach sample in all 6m 3m 2m 1m {
		*Regression with PO 
		reghdfe `x' `postvariablesaccept' `postevsdummies'  if election_`sample'==1 & nbreferrals_invN>=10, absorb(personreferral year) vce(cluster mci_uniq_id9)level(90) 
		matrix coeff1=e(b)
		matrix cov1=e(V)
		local wherecol1 = colnumb(coeff1,"peventd`time0'accept")		
		post time ("`name'")  ("`sample'") (coeff1[1,`wherecol1']) (sqrt(cov1[`wherecol1',`wherecol1'])) 
	}
}
	
postclose time

use "$paper\TimetoElection.dta", clear 

local r accept 
	gen `r'_cu= `r'_b + 1.645*`r'_se  
	gen `r'_cl=`r'_b - 1.645*`r'_se

	gen timeorder=. 
	local i=1
	foreach sample in all 6m 3m 2m 1m {
		replace timeorder=`i' if timewindow=="`sample'"
		local i=`i'+1 
	}
	label define orderlab 1 "All" 2  "6 Months" 3 "3 Months" 4 "2 Months" 5 "1 Month"
	label val timeorder orderlab 

	local r accept 

	foreach x in Voted Registered {
graph twoway (rcap `r'_cu `r'_cl timeorder if `r'_b!=. & variable=="`x'" , lcolor(edkblue%30) fcolor(edkblue%30)) (scatter `r'_b timeorder if `r'_b!=. & variable=="`x'" , msymbol(S) mcolor(edkblue)), xline(0, lcolor(gs8) lpattern(dash)) yline(0, lcolor(gs8))  xtitle("Referral Window prior to Election Date") graphregion(color(white)) bgcolor(white) ylabel(,angle(horizontal)) legend( label(1 "90% Confidence Intervals") label(2 "Estimate")) xlabel(, valuelabel labsize(small)) ytitle("`x' (percentage points)")
graph export "$paper\\TimetoVote`x'.png", replace 

}


*********************
* Pre-trends Table 
********************* 
frame change default 
tab evs_y //up to -10 

preserve 
	keep if nbreferrals_invN>=10
	keep if evs_y<0 | screenin==0 
	keep evs_y propacceptresN propopenonlyresN propanyremoved3mresN registered rep dem voted_post2013 screenin personreferral year mci_uniq_id9

	capture postclose ftests 
	postfile ftests str30 variable accept removal openonly  evs Naccept Nremoval using "$paper\PretrendsF.dta", replace
		
	local nbyearstested=2
	tab evs_y if evs_y<0 & screenin==1, gen(eventd)	
	local timebefore0 `r(r)'
	local keyvarteststart=`timebefore0'+1-`nbyearstested'
forval j=1/`r(r)' { 
	gen peventd`j'accept=propacceptresN*eventd`j'
	replace peventd`j'accept=0 if screenin==0 
	gen peventd`j'openonly=propopenonlyresN*eventd`j'
	replace peventd`j'openonly=0 if screenin==0 
	gen peventd`j'rem= propanyremoved3mresN*eventd`j'
	replace peventd`j'rem=0 if screenin==0 
}
	
	*for each outcome variable
	foreach x in registered rep dem voted_post2013 {
	local name : variable label `x' 
	
	distinct evs_y if evs_y<0 & `x'<. //maximum number of years available for this variable 
	local nbyearsused= r(ndistinct)
	
	local evsdummies 
	local variablesaccept 
	local variablesrem 
	local variablesopenonly
	local variablesacceptmedian 
	forval t=`keyvarteststart'/`timebefore0' {
		replace eventd`t'=0 if screenin==0 
		local evsdummies `evsdummies' eventd`t'
		local variablesaccept `variablesaccept' peventd`t'accept
		local variablesrem `variablesrem' peventd`t'rem
		local variablesopenonly `variablesopenonly' peventd`t'openonly
	}

		*Regression with PO 
		reghdfe `x' `variablesaccept' `evsdummies' if evs_y>=-`nbyearsused', absorb(personreferral year) vce(cluster mci_uniq_id9)level(90) 
		local N1=e(N)
		test `evsdummies' 
		local pvalbase=round(`r(p)',0.001)		
		test `variablesaccept'
		local pvalaccept=round(`r(p)',0.001)
		*Regression with PR and PNR 
		reghdfe `x' `variablesrem' `variablesopenonly' `evsdummies' if evs_y>=-`nbyearsused', absorb(personreferral year) vce(cluster mci_uniq_id9) level(90) 
		local N2=e(N)
		test `variablesrem'
		local pvalrem=round(`r(p)',0.001)
		test `variablesopenonly'
		local pvalopenonly=round(`r(p)',0.001)
		post ftests ("`name'") (`pvalaccept') (`pvalrem') (`pvalopenonly') (`pvalbase') (`N1') (`N2')
	}
postclose ftests
restore 

cap frame drop results 
frame create results 
frame change results 
use "$paper\PretrendsF.dta" 
label var accept "Opened a Case"
label var removal "Child Removed"
label var openonly "Opened a Case w/out Removal"
drop evs Nremoval
label var variable "Outcome"
order variable accept openonly removal Naccept  
eststo clear 
estpost tabstat accept openonly removal Naccept, by(variable)
esttab using "$paper\TableFtestspretrends.tex", cells("accept(label(Opened a Case) fmt(%04.3f)) openonly(label(Opened w/o Removal) fmt(%05.3f)) removal(label(Child Removed) fmt(%04.3f)) Naccept(label(N) fmt(%04.0f))") noobs nomtitles nonumbers drop(Total) varwidth(30) tex replace 
 

frame change default 
frame drop results 


***************** 
* Regression Output for Main Graphs 
***************** 


cap frame change default 
frame copy default regression, replace 
frame change regression
tab evs_y, gen(eventd)
dis `r(r)'
forval j=1/`r(r)' { 
gen peventd`j'accept=propacceptresN*eventd`j'
replace peventd`j'accept=0 if screenin==0 
gen peventd`j'openonly=propopenonlyresN*eventd`j'
replace peventd`j'openonly=0 if screenin==0 
gen peventd`j'rem= propanyremoved3mresN*eventd`j'
replace peventd`j'rem=0 if screenin==0 
}

local prenb 2  
local postnb 11
	capture postclose coef 
	postfile coef str30 variable reltime accept_b accept_se removal_b removal_se openonly_b openonly_se using "$paper\Coefficients.dta", replace
	
	tab evs_y if evs_y<=0
	local time0 `r(r)'
	local timebefore0=`time0'-1

*Variables for regressions 	
	foreach x in voted_post2013 registered {
		replace `x'=`x'*100
		local startevsnb=`time0'-`prenb'
		local endevsnb=`time0'+`postnb'
	foreach l in evsdummies variablesaccept variablesopenonly variablesrem {
		foreach prefix in pre post {
		local `prefix'`l' 
		}
	}
	foreach num of numlist `startevsnb'/`endevsnb' { 
		cap gen inveventd`num'=eventd`num'*screenin 
		*post-specification variables 
		local postevsdummies `postevsdummies' inveventd`num' 
		if `num'>=`time0' { 
			foreach u in accept openonly rem {
				local postvariables`u' `postvariables`u'' peventd`num'`u'
			}
		}
		*pre-specification variables 
		else { 
		local preevsdummies `preevsdummies' inveventd`num'
			foreach u in accept openonly rem {
				local prevariables`u' `prevariables`u'' peventd`num'`u'
			}
		}
	}


	local name : variable label `x'
	*Pre-trends analyses 
		*Regression with PO 
		reghdfe `x' `prevariablesaccept' `preevsdummies' if( (evs_y<0 & nbreferrals_invN>=10) | screenin==0), absorb(personreferral year) vce(cluster mci_uniq_id9)level(90) 
		cap test `preevsdummies' 
		local pvalbase=round(`r(p)',0.001)		
		cap test `prevariablesaccept'
		local pvalaccept=round(`r(p)',0.001)
		matrix coeff1=e(b)
		matrix cov1=e(V)
		*Regression with PR and PNR 
		reghdfe `x' `prevariablesrem' `prevariablesopenonly' `preevsdummies'  if ( (evs_y<0 & nbreferrals_invN>=10) | screenin==0), absorb(personreferral year) vce(cluster mci_uniq_id9)level(90)  
		cap test `prevariablesrem'
		local pvalrem=round(`r(p)',0.001)
		cap test `prevariablesopenonly'
		local pvalopenonly=round(`r(p)',0.001)
		matrix coeff3=e(b)
		matrix cov3=e(V)
			forval i=`startevsnb'/`timebefore0' { 
			local eventtime=`i'-`time0'
			local wherecol1 = colnumb(coeff1,"peventd`i'accept")
			local wherecol3 = colnumb(coeff3,"peventd`i'rem")
			local wherecol4 = colnumb(coeff3,"peventd`i'openonly")
			post coef ("`name'")  (`eventtime') (coeff1[1,`wherecol1']) (sqrt(cov1[`wherecol1',`wherecol1'])) (coeff3[1,`wherecol3']) (sqrt(cov3[`wherecol3',`wherecol3'])) (coeff3[1,`wherecol4']) (sqrt(cov3[`wherecol4',`wherecol4'])) 
			}

	*Post-trends analyses 
		*Regression with PO 
		reghdfe `x' `postvariablesaccept' `postevsdummies'  if nbreferrals_invN>=10, absorb(personreferral year) vce(cluster mci_uniq_id9)level(90) 
		matrix coeff1=e(b)
		matrix cov1=e(V)
		*Regression with PR and PNR 
		reghdfe `x' `postvariablesrem' `postvariablesopenonly' `postevsdummies'   if  nbreferrals_invN>=10, absorb(personreferral year) vce(cluster mci_uniq_id9)level(90)  
		matrix coeff3=e(b)
		matrix cov3=e(V)
		forval i=`time0'/`endevsnb' {
				local eventtime=`i'-`time0'
				local wherecol1 = colnumb(coeff1,"peventd`i'accept")
				local wherecol3 = colnumb(coeff3,"peventd`i'rem")
				local wherecol4 = colnumb(coeff3,"peventd`i'openonly")
			post coef ("`name'")  (`eventtime') (coeff1[1,`wherecol1']) (sqrt(cov1[`wherecol1',`wherecol1'])) (coeff3[1,`wherecol3']) (sqrt(cov3[`wherecol3',`wherecol3'])) (coeff3[1,`wherecol4']) (sqrt(cov3[`wherecol4',`wherecol4'])) 
	}
}
	
postclose coef

*****************************
* Graphs for Black Americans 
*****************************
eststo clear 
local x accept 
rename peventd9`x' pre2`x'
rename peventd10`x' pre1`x'
forval i=11/19 { 
    local newid=`i'-11
    rename peventd`i'`x' post`newid'`x'
}

preserve 
local outcome voted_post2013
reghdfe `outcome' pre*accept  inveventd*  if evs_y<=8 & black==1  &(( nbreferrals_invN>=10&evs_y<0) | screenin==0), absorb(personreferral year) vce(cluster mci_uniq_id9)level(90) 
estimates store mpre
reghdfe `outcome' post*accept inveventd*  if  evs_y<=8 & black==1  &( nbreferrals_invN>=10 | screenin==0), absorb(personreferral year) vce(cluster mci_uniq_id9)level(90)
estimates store mpost

event_plot mpre mpost, stub_lead(pre#accept) stub_lag(post#accept) plottype(connected) alpha(0.10) graph_opt(xtitle("Years relative to referral") ytitle("Voted") xline(0, lcolor(gs8) lpattern(dash)) yline(0, lcolor(gs8)) graphregion(color(white)) bgcolor(white) ylabel(,angle(horizontal))) lag_opt(color(edkblue)) lead_opt(color(orange) msymbol(S)) lag_ci_opt(color(eltblue%30 eltblue%30)) lead_ci_opt(color(orange%30 orange%30)) legend_opt(region(lstyle(none))) 
graph export "$paper\\Votedpost2013Black.png", replace 

local outcome registered
reghdfe `outcome' pre*accept  inveventd*  if evs_y<=8 & black==1  &(( nbreferrals_invN>=10&evs_y<0) | screenin==0), absorb(personreferral year) vce(cluster mci_uniq_id9)level(90) 
estimates store mpre
reghdfe `outcome' post*accept inveventd*  if  evs_y<=8 & black==1  &( nbreferrals_invN>=10 | screenin==0), absorb(personreferral year) vce(cluster mci_uniq_id9)level(90)
estimates store mpost

event_plot mpre mpost, stub_lead(pre#accept) stub_lag(post#accept) plottype(connected) alpha(0.10) graph_opt(xtitle("Years relative to referral") ytitle("Registered") xline(0, lcolor(gs8) lpattern(dash)) yline(0, lcolor(gs8)) graphregion(color(white)) bgcolor(white) ylabel(,angle(horizontal))) lag_opt(color(edkblue)) lead_opt(color(orange) msymbol(S)) lag_ci_opt(color(eltblue%30 eltblue%30)) lead_ci_opt(color(orange%30 orange%30)) legend_opt(region(lstyle(none))) 
graph export "$paper\\RegisteredBlack.png", replace 

restore 




****************** 
* Graphs of Main Results 
****************** 

use "$paper\Coefficients.dta", clear
duplicates report reltime variable 
compress 

foreach r in accept removal openonly { 
	gen `r'_cu= `r'_b + 1.645*`r'_se  
	gen `r'_cl=`r'_b - 1.645*`r'_se
} 

sort variable reltime 


foreach r in accept removal { 
graph twoway (rarea `r'_cu `r'_cl reltime if `r'_b!=. & reltime<0 & variable=="Voted" , lcolor(orange%30) fcolor(orange%30)) (connected `r'_b reltime if `r'_b!=. & reltime<0& variable=="Voted" , msymbol(S) mcolor(orange))(rarea `r'_cu `r'_cl reltime if `r'_b!=. & reltime>=0 & variable=="Voted"  , lcolor(eltblue%30) fcolor(eltblue%30)) (connected `r'_b reltime if `r'_b!=. & reltime>=0 & variable=="Voted" , msymbol(O) lcolor(edkblue) mcolor(edkblue)), xline(0, lcolor(gs8) lpattern(dash)) yline(0, lcolor(gs8)) ytitle("Voted") xlab(-3(3)12) xtitle("Years relative to referral") graphregion(color(white)) bgcolor(white) ylabel(,angle(horizontal)) legend(order(2 4) label(2 "Pre-trend coefficients") label(4 "Treatment effects"))

graph export "$paper\\Votedpost2013`r'.png", replace 

graph twoway (rarea `r'_cu `r'_cl reltime if `r'_b!=. & reltime<0 & variable=="Registered" , lcolor(orange%30) fcolor(orange%30)) (connected `r'_b reltime if `r'_b!=. & reltime<0& variable=="Registered"  , msymbol(S) mcolor(orange))(rarea `r'_cu `r'_cl reltime if `r'_b!=. & reltime>=0 & variable=="Registered" , lcolor(eltblue%30) fcolor(eltblue%30)) (connected `r'_b reltime if `r'_b!=. & reltime>=0 & variable=="Registered"  , msymbol(O) lcolor(edkblue) mcolor(edkblue)), xline(0, lcolor(gs8) lpattern(dash)) yline(0, lcolor(gs8)) ytitle("Registered") xlab(-3(3)12) xtitle("Years relative to referral") graphregion(color(white)) bgcolor(white) ylabel(,angle(horizontal)) legend(order(2 4) label(2 "Pre-trend coefficients") label(4 "Treatment effects"))

graph export "$paper\\Registered`r'.png", replace 
}

*Rescaled version to q1 to q3 
foreach r in accept removal { 
	foreach x in `r'_b `r'_cu `r'_cl  {
		replace `x'=`x'*0.1487513
	}
graph twoway (rarea `r'_cu `r'_cl reltime if `r'_b!=. & reltime<0 & variable=="Voted" , lcolor(orange%30) fcolor(orange%30)) (connected `r'_b reltime if `r'_b!=. & reltime<0& variable=="Voted" , msymbol(S) mcolor(orange))(rarea `r'_cu `r'_cl reltime if `r'_b!=. & reltime>=0 & variable=="Voted"  , lcolor(eltblue%30) fcolor(eltblue%30)) (connected `r'_b reltime if `r'_b!=. & reltime>=0 & variable=="Voted" , msymbol(O) lcolor(edkblue) mcolor(edkblue)), xline(0, lcolor(gs8) lpattern(dash)) yline(0, lcolor(gs8)) ytitle("Voted") xlab(-3(3)12) xtitle("Years relative to referral") graphregion(color(white)) bgcolor(white) ylabel(,angle(horizontal)) legend(order(2 4) label(2 "Pre-trend coefficients") label(4 "Treatment effects"))

graph export "$paper\\Votedpost2013`r'p25p75.png", replace 

graph twoway (rarea `r'_cu `r'_cl reltime if `r'_b!=. & reltime<0 & variable=="Registered" , lcolor(orange%30) fcolor(orange%30)) (connected `r'_b reltime if `r'_b!=. & reltime<0& variable=="Registered"  , msymbol(S) mcolor(orange))(rarea `r'_cu `r'_cl reltime if `r'_b!=. & reltime>=0 & variable=="Registered" , lcolor(eltblue%30) fcolor(eltblue%30)) (connected `r'_b reltime if `r'_b!=. & reltime>=0 & variable=="Registered"  , msymbol(O) lcolor(edkblue) mcolor(edkblue)), xline(0, lcolor(gs8) lpattern(dash)) yline(0, lcolor(gs8)) ytitle("Registered") xlab(-3(3)12) xtitle("Years relative to referral") graphregion(color(white)) bgcolor(white) ylabel(,angle(horizontal)) legend(order(2 4) label(2 "Pre-trend coefficients") label(4 "Treatment effects"))

graph export "$paper\\Registered`r'p25p75.png", replace 
}



****************
* Power calculations 
**************** 
cap frame change default 
cap frame drop power
frame copy default power, replace 
frame change power 


cap drop *after 
gen after=evs_y>=0 
replace after=0 if screenin==0 
foreach x in propacceptresN propopenonlyresN propanyremoved3mresN  {
	gen `x'after=`x'*after 
	replace `x'after=0 if screenin==0 
}

drop if nbreferrals_invN<10 


*Changing data format to be able to test both margins of interventions on both outcomes 
expand 2, gen(orig) 
gen outcome=registered if orig==0 
replace outcome=voted_post2013 if orig==1 
egen newperson=group(personreferral orig)
egen newyear=group(year orig)

*Can I reject that all the coefficients are 0? No. 
cap drop eb er yrhat ybhat sample 
reghdfe outcome c.propanyremoved3mresNafter##orig c.propopenonlyresNafter##orig  after##orig if  ( nbreferrals_invN>=10), absorb(newperson newyear) level(90) residuals(eb)  //vce(cluster mci_uniq_id9) 
local nobsnoclust=e(N)
gen sample=e(sample)
local db= e(df_r)
local ssb=e(rss)
predict ybhat if sample==1, xb 

test 1.orig#propanyremoved3mresNafter 1.orig#propopenonlyresNafter propanyremoved3mresNafter propopenonlyresNafter
/*  F(  4, 90517) =    0.96
            Prob > F =    0.4281
dis Ftail(4, 90517,0.96)
*/ 
local Fstat=r(F)
local pval=string(r(p),"%9.2f")

reghdfe outcome  after##orig if sample==1 & ( nbreferrals_invN>=10), absorb(newperson newyear) level(90) residuals(er) // vce(cluster mci_uniq_id9) 
local dr= e(df_r)
local ssr=e(rss)
predict yrhat if sample==1, xb 


local Fcrit=(`ssr'-`ssb')/`ssb'*`db'/4
dis "F:"`Fcrit', "SSR:"`ssr', "SSB:"`ssb', "DR:"`dr', "DB:"`db'
//the degrees of freedom calculation from reghdfe for df_r uses the number of clusters -1 

*What is the power of this test? 
cap drop num 
summ eb, det 
local variance=r(Var)  
gen num=(ybhat-yrhat)^2 
summ num 
local np=`r(sum)'/`variance'
local power=string(nFtail(4, `db',`np', `Fstat'),"%9.2f")
dis `power', `np'

reghdfe outcome c.propanyremoved3mresNafter##orig c.propopenonlyresNafter##orig  after##orig if  ( nbreferrals_invN>=10), absorb(newperson newyear) level(90) vce(cluster mci_uniq_id9) 
local nobsclust=e(N)
local nclust=e(N_clust)


test 1.orig#propanyremoved3mresNafter 1.orig#propopenonlyresNafter propanyremoved3mresNafter propopenonlyresNafter
local pvalcluster=string(r(p),"%9.2f")


cap erase "$paper\TablePower.tex"
file open myfile using "$paper\TablePower.tex", write replace
file write myfile "{"  _n
file write myfile "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n
file write myfile "\begin{longtable}{l*{2}{c}}" _n 
file write myfile "\toprule\endfirsthead\midrule\endhead\midrule\endfoot\endlastfoot" _n 
file write myfile " &\multicolumn{1}{c}{(1)} &\multicolumn{1}{c}{(2)}\\" _n 
file write myfile "& With Clustering & No Clustering\\" _n 
file write myfile  "\midrule" _n


	file write myfile "F-test pvalue & `pvalcluster' & `pval' \\" _n 
	file write myfile "Test's Statiscal Power & &`power' \\" _n
	file write myfile "\hline" _n
	file write myfile "Number of Observations & `nobsclust' & `nobsnoclust' \\" _n	
	file write myfile "Number of Clusters & `nclust' & \\" _n
	file write myfile "\bottomrule" _n
file write myfile "\end{longtable}" _n
file write myfile "}" _n
file close myfile
